import React, { useContext, useEffect, useState } from 'react';
import {
  DatePicker,
  Empty,
  Input,
  Modal,
  Skeleton,
  Typography,
} from '@arco-design/web-react';
import useLocale from '@/utils/useLocale';
import locale from './locale';
import styles from './style/index.module.less';
import { ActionLog } from '@/api/modules/violation';
import cs from 'classnames';
import { GlobalContext } from '@/context';
import { IconSearch } from '@arco-design/web-react/icon';
import Files from '@/assets/icon_files.svg';
import { showDoc, usedownloadDoc } from '@/utils/useDownload';
import { debounce } from 'lodash';
import dayjs from 'dayjs';
import ModalTitle from '@/components/ModalTitle';
import { GlobalState } from '@/store';
import { useSelector } from 'react-redux';
import has from 'lodash/has';

function SupportingCreate({
  visible,
  onVisible,
  refNumber,
}: {
  visible: boolean;
  refNumber: string;
  onVisible: (status: boolean) => void;
}) {
  const { rtl, lang } = useContext(GlobalContext);
  const t = useLocale(locale);
  const [listData, setListData] = useState([]);
  const [showListData, setShowListData] = useState([]);
  const [loading, setLoading] = useState<boolean>(false);

  const onCancel = () => {
    onVisible(false);
  };

  const fetchData = () => {
    setLoading(true);
    ActionLog({ refNumber: refNumber, q: q })
      .then((res) => {
        setListData(res.data);
        setLoading(false);
      })
      .catch(() => {
        setLoading(false);
      });
  };

  useEffect(() => {
    if (visible) {
      setQ('');
      fetchData();
      return;
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [visible]);

  const [q, setQ] = useState('');
  const [date, setDae] = useState({ start: 0, end: 0 });
  const handleSearch = debounce((e) => {
    setQ(e);
  }, 300);

  useEffect(() => {
    if (listData.length > 0) {
      const list = listData.filter((a) => {
        let str = '';
        if (a.actionType) {
          str = a.actionType;
        }
        if (a.comments) {
          str = str + a.comments;
        }
        if (a.attachments) {
          str = str + a.attachments;
        }
        if (a.createdBy) {
          str = str + a.createdBy.name;
        }
        if (a.violationReplyVoo) {
          str = str + a.violationReplyVoo.content;
        }
        const second = dayjs(dayjs(a.createdAt).format('YYYY-MM-DD')).unix();
        const isTime =
          date.end === 0 && date.start === 0
            ? true
            : second <= date.end && second >= date.start;

        return (
          str && str.toLowerCase().includes(q.trim().toLowerCase()) && isTime
        );
      });
      setShowListData(list);
    }
  }, [listData, q, date]);

  const actionKey = {
    assignedPerson: t['actions.person'],
    violationType: t['actions.type'],
    status: t['actions.status'],
    actionTaken: t['actions.taken'],
    actionType: t['actions.type'],
    sendBackEntity: t['actions.sendToEntity'],
    sendSms: t['actions.sms'],
    sendSAI: t['actions.sendToSAI'],
    sendForesight: t['actions.sendToForesight'],
    sendLocal: t['allHistory.sendTolocal'],
    localEmirate: t['actions.authority'],
  };

  const handleSearchDate = debounce((e) => {
    let start = 0;
    let end = 0;
    if (e) {
      start = dayjs(e[0]).unix();
      end = dayjs(e[1]).unix();
    }
    setDae(() => ({
      start,
      end,
    }));
  }, 300);

  const formatActionsValue = (item) => {
    let value = '';
    if (item instanceof Object && item.hasOwnProperty('value')) {
      value = String(item.value[lang === 'en-US' ? 'en' : 'ar']);
    } else if (item instanceof String) {
      value = String(item);
    } else if (item instanceof Array) {
      value = item
        .map((a) => {
          let val = '';
          if (a instanceof Object && a.hasOwnProperty('value')) {
            val = String(a.value[lang === 'en-US' ? 'en' : 'ar']);
          }
          if (a instanceof Object && a.hasOwnProperty('name')) {
            val = String(a.name);
          }
          if (a instanceof String) {
            val = String(a);
          }
          return val;
        })
        .join('，');
    } else {
      value = item ? 'True' : 'False';
    }
    return value;
  };

  const formatActions = (vals, oldVals) => {
    const actions = [];
    for (const key in actionKey) {
      const item: any = {};
      item.key = key;
      item.label = actionKey[key];
      //查找老数据
      for (const oldVal of oldVals) {
        for (const oldValKey of Object.keys(oldVal)) {
          if (key === oldValKey) {
            item.oldValue = formatActionsValue(oldVal[oldValKey]);
          }
        }
      }
      //查找老数据
      for (const val of vals) {
        for (const valKey of Object.keys(val)) {
          if (key === valKey) {
            item.value = formatActionsValue(val[valKey]);
          }
        }
      }
      if (item.hasOwnProperty('value') || item.hasOwnProperty('oldValue')) {
        actions.push(item);
      }
    }

    return actions;
  };

  const actions = useSelector((state: GlobalState) => state.actions);

  //其他回复的枚举
  const actionOtherType = {
    OPEN: { name: 'Open Violation', nameAr: 'فتح المخالفة' },
    OPEN_COMMENTS_HISTORY: {
      name: 'Open Comments History',
      nameAr: ' فتح سجل التعليقات',
    },
    OPEN_INVESTIGATION: { name: 'Open Investigation', nameAr: 'تحقيق عام' },
    OPEN_ALL_HISTORY: { name: 'Open ALL History', nameAr: 'فتح كل التاريخ' },
    DOWNLOAD_MASTER_REPORT: {
      name: 'Download Master Report',
      nameAr: 'تحميل التقرير الرئيسي',
    },
    DOWNLOAD_INVESTIGATION: {
      name: 'Download Investigation',
      nameAr: 'تحميل تقرير التحقيق',
    },
  };

  return (
    <div>
      <Modal
        title={<ModalTitle title={t['allHistory.title']} />}
        style={{ width: '870px' }}
        visible={visible}
        onCancel={() => onCancel()}
        maskClosable={false}
        unmountOnExit={true}
        footer={null}
        className={cs(styles['history'], rtl ? 'rtl' : '')}
      >
        <div className={styles['history-search1']}>
          <Input
            style={{ width: 288 }}
            suffix={<IconSearch />}
            allowClear
            placeholder={t['commmitsHistory.search']}
            onChange={handleSearch}
          />
          <div className={styles['history-search1-date']}>
            <DatePicker.RangePicker
              onChange={handleSearchDate}
              allowClear
              style={{ width: 288 }}
              format="YYYY-MM-DD"
              disabledDate={(date) => dayjs(date).isAfter(dayjs())}
            />
          </div>
        </div>

        <Skeleton
          loading={loading}
          style={{ width: '90%', margin: '20px auto' }}
          text={{ rows: 7 }}
          animation
        >
          {showListData.length === 0 ? (
            <div className={styles['history-empty']}>
              <Empty description={t['empty.noData']} />
            </div>
          ) : (
            <div className={styles['history-scroll']}>
              {showListData.map((a, index) => (
                <div className={styles['item']} key={index}>
                  <div className={styles['item-header']}>
                    <div className={styles['name']}>
                      <span className={styles['text']}>
                        {a.createdBy?.name ||
                          (a.violationReplyVoo &&
                            a.violationReplyVoo[
                              lang === 'en-US' ? 'createdBy' : 'createdByAr'
                            ])}
                      </span>
                    </div>
                    <div className={styles['time']}>{a.createdAt}</div>
                  </div>
                  {/* Other */}
                  {has(actionOtherType, a.actionType) && (
                    <div className={styles['item-commit']}>
                      <div className={styles['item-commit-header']}>
                        <div className={styles['name']}>
                          {t['allHistory.actions']}：
                          {
                            actionOtherType[a.actionType][
                              lang == 'en-US' ? 'name' : 'nameAr'
                            ]
                          }
                        </div>
                      </div>
                    </div>
                  )}
                  {/* UPDATE */}
                  {a.actionType === 'UPDATE' && (
                    <>
                      {/* actions */}
                      {((a.actions && a.actions.length > 0) ||
                        (a.actions0 && a.actions0.length > 0)) && (
                        <div className={styles['item-commit']}>
                          <div className={styles['item-commit-header']}>
                            <div className={styles['name']}>
                              {t['allHistory.actions']}:
                            </div>
                          </div>
                          <div
                            className={cs(
                              styles['item-commit-content'],
                              styles['action'],
                              rtl ? styles['item-commit-content-rtl'] : ''
                            )}
                          >
                            {formatActions(a.actions, a.actions0).map(
                              (b, key) => {
                                return (
                                  <div
                                    key={key}
                                    className={styles['action-item']}
                                  >
                                    <span className={styles['action-label']}>
                                      {b.label}：
                                    </span>

                                    <Typography.Text delete>
                                      {b.oldValue}
                                    </Typography.Text>
                                    {b.hasOwnProperty('value') &&
                                      b.hasOwnProperty('oldValue') && (
                                        <span style={{ padding: '0 6px' }}>
                                          -&gt;
                                        </span>
                                      )}
                                    {/* 新值 */}
                                    <span className={styles['action-value']}>
                                      {b.value}
                                    </span>
                                  </div>
                                );
                              }
                            )}
                          </div>
                        </div>
                      )}

                      {/* commented */}
                      {a.comments && (
                        <>
                          <div className={styles['item-hr']}></div>
                          <div className={styles['item-commit']}>
                            <div className={styles['item-commit-header']}>
                              <div className={styles['name']}>
                                {t['allHistory.commented']}:
                              </div>
                            </div>
                            <div className={styles['item-commit-content']}>
                              {a.comments}
                            </div>
                          </div>
                        </>
                      )}

                      {/* attachments */}
                      {a.attachments && (
                        <>
                          <div className={styles['item-hr']}></div>
                          <div className={styles['item-files']}>
                            {a.attachments.split(',').map((b, index) => (
                              <div key={index} className={styles['file_bg']}>
                                <div
                                  className={styles['file']}
                                  onClick={() => {
                                    if (
                                      actions.includes(
                                        'violation.detail.file/link'
                                      )
                                    ) {
                                      usedownloadDoc(b);
                                    }
                                  }}
                                >
                                  <Files className={styles['icon']} />
                                  <span
                                    className={cs(styles['span'], 'ellipsis')}
                                  >
                                    {b}
                                  </span>
                                </div>
                              </div>
                            ))}
                          </div>
                        </>
                      )}
                    </>
                  )}

                  {/* REPLY */}
                  {a.actionType === 'REPLY' && (
                    <>
                      {/* commented */}
                      {a.violationReplyVoo.content && (
                        <>
                          <div className={styles['item-hr']}></div>
                          <div className={styles['item-commit']}>
                            <div className={styles['item-commit-header']}>
                              <div className={styles['name']}>
                                {t['allHistory.commentedentity']}:
                              </div>
                            </div>
                            <div className={styles['item-commit-content']}>
                              {a.violationReplyVoo.content}
                            </div>
                          </div>
                        </>
                      )}

                      {/* attachments */}
                      {a.violationReplyVoo.attachment &&
                        a.violationReplyVoo.attachment.length > 0 && (
                          <>
                            <div className={styles['item-hr']}></div>
                            <div className={styles['item-files']}>
                              {a.violationReplyVoo.attachment.map(
                                (b, index) => (
                                  <div
                                    key={index}
                                    className={styles['file_bg']}
                                  >
                                    <div
                                      className={styles['file']}
                                      onClick={() => {
                                        if (
                                          actions.includes(
                                            'violation.detail.file/link'
                                          )
                                        ) {
                                          usedownloadDoc(b);
                                        }
                                      }}
                                    >
                                      <Files className={styles['icon']} />
                                      <span
                                        className={cs(
                                          styles['span'],
                                          'ellipsis'
                                        )}
                                      >
                                        {b}
                                      </span>
                                    </div>
                                  </div>
                                )
                              )}
                            </div>
                          </>
                        )}
                    </>
                  )}
                </div>
              ))}
            </div>
          )}
        </Skeleton>
      </Modal>
    </div>
  );
}

export default SupportingCreate;
